package SpgBI_Dec.Biz;

import SpgBI_Dec.Common.DBUtils;
import org.apache.log4j.MDC;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Cubas {
    private static Logger _log = LoggerFactory.getLogger(Cubas.class);

    public static String CreateCubasDocument(String VoucherID,String Unit,String CustCode,String CustName){
        XMLWriter writer = null;
        String resFile = "";
        try{
            Document Doc = DocumentHelper.createDocument();
            org.dom4j.Element elUfinterface = Doc.addElement("ufinterface");

            elUfinterface.addAttribute("billtype", "bscubas");
            elUfinterface.addAttribute("isexchange","Y");
            elUfinterface.addAttribute("proc","add");
            elUfinterface.addAttribute("receiver",Unit);
            elUfinterface.addAttribute("replace","N");
            elUfinterface.addAttribute("roottag","");
            elUfinterface.addAttribute("sender","0101");
            elUfinterface.addAttribute("subbilltype","");
            org.dom4j.Element elBasdoc = elUfinterface.addElement("basdoc");

            elBasdoc.addAttribute("id", "");

            org.dom4j.Element elBasdoc_head = elBasdoc.addElement("basdoc_head");
            elBasdoc_head.addElement("pk_corp").setText(Unit);
            elBasdoc_head.addElement("pk_areacl").setText("02");
            elBasdoc_head.addElement("custcode").setText(CustCode);
            elBasdoc_head.addElement("custname").setText(CustName);
            elBasdoc_head.addElement("custprop").setText("0");
            elBasdoc_head.addElement("custshortname").setText(CustName);
            elBasdoc_head.addElement("memo").setText("");
            elBasdoc_head.addElement("custtype").setText("2");

            OutputFormat XML_FORMAT = new OutputFormat();
            // 设置换行 为false时输出的xml不分行
            XML_FORMAT.setNewlines(true);
            // 生成缩进
            XML_FORMAT.setIndent(true);
            // 指定使用tab键缩进
            XML_FORMAT.setIndent("  ");
            XML_FORMAT.setEncoding("gb2312");
            //XMLWriter writer = new XMLWriter(format);
            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
            resFile = "d:/data/cubas/cubas_" + fmt.format(new Date()) + ".xml";
            File file = new File(resFile);
            writer = new XMLWriter(new FileOutputStream(file), XML_FORMAT);
            //BufferedInputStream input = new BufferedInputStream(format);
            writer.write(Doc);
        }catch (Exception ex){
            resFile = "";
        }finally {
            if (writer != null) writer = null;
            //DBUtils.close(connFIN);
            return resFile;
        }
    }

    public static Map<String,String> ExchangeCubasData(String VoucherID, String Unit, String CustCode, String CustName){
        MDC.put("VOUCHERID",VoucherID);
        Connection connFIN = null;
        PreparedStatement pstmtCubas = null;
        ResultSet rsCubas = null;
        String url = "http://172.22.6.7:80/service/XChangeServlet?account=02";
        File file = null;
        StringBuffer Msg = new StringBuffer();
        String resSuc = "U";
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
        Map<String,String> mapRet = null;
        try {
            mapRet = new HashMap<>();
            Msg.append(fmt.format(new Date()) + ",开始向nc传输客商单据" +"\n");
            connFIN = DBUtils.getConnection("FINSERVER");
            pstmtCubas = connFIN.prepareStatement("SELECT * FROM bd_cubasdoc where pk_corp = ? AND custcode = ?");
            pstmtCubas.setString(1,Unit);
            pstmtCubas.setString(2,CustCode);
            rsCubas = pstmtCubas.executeQuery();
            if (rsCubas.next()){
                Msg.append("已存在对应客商，不再新建客商");
                resSuc = "Y";
                return mapRet;
            }

            URL realURL = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) realURL.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-type", "text/xml");
            connection.setRequestMethod("POST");
            String srcFile = CreateCubasDocument(VoucherID,Unit,CustCode,CustName);
            if ("".equals(srcFile)){
                Msg.append("创建客商交换文档时出错，具体信息请查看日志。");
                return mapRet;
            }else {
                file = new File(srcFile);
            }

            BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
            BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
            int length;
            byte[] buffer = new byte[1000];
            while ((length = input.read(buffer, 0, 1000)) != -1) {
                out.write(buffer, 0, length);
            }
            input.close();
            out.close();

            Msg.append("等待NC返回传输结果\n");
            // 从连接的输入流中取得回执信息
            /***************从输入流取得Doc***************/
            InputStream inputStream = connection.getInputStream();

            InputStreamReader isr = new InputStreamReader(inputStream);
            BufferedReader bufreader = new BufferedReader(isr);
            String xmlString = "";
            int c;
            //System.out.println("==================Beging====================");
            while ((c = bufreader.read()) != -1) {
                //System.out.print((char) c);
                xmlString += (char) c;
            }
            input.close();
            //System.out.println("===================End======================");
            Document resDoc = DocumentHelper.parseText(xmlString);


            // 对回执结果的后续处理
            /************document转化为xml*************/
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            DocumentSource source = new DocumentSource(resDoc);
            transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
            //设置文档的换行与缩进
            transformer.setOutputProperty(OutputKeys.INDENT, "YES");


            //设置日期格式
            String resFile = "D:/data/bkmsg/BkMsg_Cubas_" + fmt.format(new Date()) + ".xml";
            StreamResult result = new StreamResult(new File(resFile));
            transformer.transform(source, result);
            //System.out.println("======生成回执文件成功=======");
            Msg.append("已取得NC返回传输结果，解析结果如下：\n");

            /**************jdom解析XML*****************/
            SAXBuilder saxReader = new SAXBuilder();
            org.jdom2.Document document1 = saxReader.build(new File(resFile));
            org.jdom2.Element root = document1.getRootElement();
            //获取根元素,得到导入用友是否成功successful的值,值为Y:成功 N:失败
            resSuc = root.getAttributeValue("successful");

            //后面对回执结果做判断,然后改变导入状态就行了
            if (null != resSuc) {
                if (resSuc.equals("N")) {
                    Msg.append("导入失败,信息如下：\n");
                } else if (resSuc.equals("Y")) {
                    Msg.append("导入成功,,信息如下：\n");
                } else {
                    Msg.append("返回异常状态,,信息如下：\n");
                    resSuc = "U";
                }
            } else {
                Msg.append("返回异常状态,,信息如下：\n");
                resSuc = "U";
            }

            List<Element> list = root.getChildren();
            for (org.jdom2.Element e : list) {
                Msg.append(e.getChildText("resultdescription"));
                Msg.append("\n");
                Msg.append(e.getChildText("content"));
                Msg.append("\n");
            }
            //file.delete();
        } catch (Exception ex)
        {
            ex.printStackTrace();
            _log.error(ex.getStackTrace().toString());
            Msg.append("传输时出错，请查看日志");
            resSuc =  "U";
        }
        finally {
            mapRet.put("RESULTS",resSuc);
            mapRet.put("MESSAGE",Msg.toString());
            Msg = null;
            return  mapRet;

        }

    }
}
